package com.gimi.cloud.bbp.commonService.mq.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.AbstractMessageConverter;
import org.springframework.util.MimeType;

import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * rabbitMq fastJson实现
 *
 * @author wbj
 * @version 1.0
 * @Description
 * @create 2018-01-11
 **/
public class MappingFastJson2MessageCoverter extends AbstractMessageConverter {
    private static final Logger logger = LoggerFactory.getLogger(MappingFastJson2MessageCoverter.class);

    /**
     * 设置默认的mimetype
     */
    public MappingFastJson2MessageCoverter() {
        super(new MimeType("application", "json", Charset.forName("UTF-8")));
    }

    /**
     * 设置支持的mimetype
     * @param supportedMimeTypes
     */
    public MappingFastJson2MessageCoverter(MimeType... supportedMimeTypes) {
        super(Arrays.asList(supportedMimeTypes));
    }

    /**
     * 判断是否可以把message转化为class
     * @param message
     * @param targetClass
     * @return
     */
    @Override
    protected boolean canConvertFrom(Message<?> message, Class<?> targetClass) {
        //如果转换的class为空，或则当前类型是不支持的mimetype 直接返回
        if (targetClass == null || !supportsMimeType(message.getHeaders())) {
            return false;
        }
        return true;
    }

    /**
     * 判断是否消息数据是否可以转化为json串
     * @param payload
     * @param headers
     * @return
     */
    @Override
    protected boolean canConvertTo(Object payload, MessageHeaders headers) {
        if (payload == null || !supportsMimeType(headers)) {
            return false;
        }
        try{
            JSON.toJSONString(payload);
        }catch(Exception e){
            logger.info(payload.getClass().getName() +"无法转化为JSON串");
            return false;
        }
        return true;
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        throw new UnsupportedOperationException();
    }

    /**
     * 将指定消息转化为指定class
     * @param message
     * @param targetClass
     * @param conversionHint
     * @return
     */
    @Override
    protected Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint) {
        Object payload = message.getPayload();
        if(null == payload){
            try{
                return targetClass.newInstance();
            }catch(Exception e){
                return null;
            }
        }
        try {
            String payloadJosnStr = "";
            if (payload instanceof byte[]) {
                payloadJosnStr = new String((byte[])payload);
            }else{
                payloadJosnStr = JSON.toJSONString(payload);
            }
            logger.info("转化json串："+JSON.toJSONString(payloadJosnStr));
            payload = JSONObject.parseObject(payloadJosnStr,targetClass);
        }catch(Exception e){
            logger.info("不支持的消息格式");
            e.printStackTrace();
        }
        return payload;
    }

    /**
     * 把指定消息在转化为json串
     * @param payload
     * @param headers
     * @param conversionHint
     * @return
     */
    @Override
    protected Object convertToInternal(Object payload, MessageHeaders headers, Object conversionHint) {
        if(null == payload){
            return new JSONObject();
        }
        logger.info("开始序列化json串");
        payload = JSON.toJSONString(payload);
        return payload;
    }
}
